from contextlib import asynccontextmanager
from fastapi import FastAPI
from loguru import logger
from utils.cache import TLLRedis
import consul
import uuid
from utils.tll_consul import ConsulClient
from utils.consul_cleanup import start_consul_cleanup, stop_consul_cleanup

client=ConsulClient()
   
@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.add("logs/file.log", level="INFO",rotation="500 MB",enqueue=True)
    
    # 注册当前服务
    client.register_service("user_api")

    # 发现用户服务地址
    addresses=await client.fetch_user_service_addresses(only_healthy=True)
    logger.info(f"已发现的健康userservers 地址：{addresses}")
    await start_consul_cleanup()

    yield
    
    # 应用关闭时的清理工作
    redis_instance = TLLRedis()
    await redis_instance.close()
    await stop_consul_cleanup()

    # 注销当前服务
    client.deregister_service()
